<template>
  <div class="block" v-title data-title="书湘-登录">
    <div class="login">
      <el-card class="box-card">
        <div slot="header" class="clearfix">登录</div>
        <el-tabs v-model="currentIndex" @tab-click="handleTabsClick">
          <el-tab-pane label="密码登录" name="login1">
            <el-form
              :model="loginForm1"
              status-icon
              :rules="rules"
              ref="loginForm1"
            >
              <el-form-item label="账号" label-width="120px" prop="username">
                <el-col :span="18">
                  <el-input
                    type="text"
                    @input="accountInput"
                    placeholder="请输入用户名/手机号"
                    v-model="loginForm1.username"
                  />
                </el-col>
              </el-form-item>
              <el-form-item label="密码" label-width="120px" prop="password">
                <el-col :span="18">
                  <el-input
                    show-password
                    @input="passwordInput"
                    type="password"
                    placeholder="请输入密码"
                    v-model="loginForm1.password"
                  />
                </el-col>
              </el-form-item>
              <el-form-item>
                <div class="button">
                  <el-button
                    type="primary"
                    style="width: 150px"
                    @click="submitForm('loginForm1')"
                  >
                    登录
                  </el-button>
                </div>
              </el-form-item>
              <div>
                <el-link @click="retrievePWD" target="_blank">忘记密码</el-link>
                <el-link style="width: 120px" @click="toRegister">
                  注册
                </el-link>
              </div>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="短信登录" name="login2">
            <el-form
              :model="loginForm2"
              status-icon
              :rules="rules"
              ref="loginForm2"
            >
              <el-form-item label="手机号" label-width="120px" prop="phone">
                <el-col :span="18">
                  <el-input
                    type="text"
                    @input="phoneInput"
                    placeholder="请输入手机号"
                    v-model="loginForm2.phone"
                  />
                </el-col>
              </el-form-item>
              <el-form-item label="验证码" label-width="120px" prop="loginword">
                <div>
                  <el-col :span="18" style="text-align: left">
                    <el-input
                      type="loginword"
                      @input="loginWordInput"
                      placeholder="请输入验证码"
                      style="width: 153px"
                      v-model="loginForm2.loginword"
                    />
                    <el-button
                      icon="el-icon-mobile-phone"
                      @click="getCode"
                      style="width: 98.5px; padding: 0px; height: 40px"
                      type="success"
                      :disabled="(disabled = !show)"
                    >
                      <span v-show="show">获取验证码</span>
                      <span v-show="!show" class="count">{{ count }} s</span>
                    </el-button>
                  </el-col>
                </div>
              </el-form-item>
              <el-form-item>
                <div class="button">
                  <el-button
                    type="primary"
                    style="width: 150px;"
                    @click="submitForm('loginForm2')"
                  >
                    登录
                  </el-button>
                </div>
              </el-form-item>
              <div>
                <el-link @click="retrievePWD" target="_blank">忘记密码</el-link>
                <el-link style="width: 120px" @click="toRegister">
                  注册
                </el-link>
              </div>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import api from "../api";
import { mapMutations } from "vuex";
export default {
  data() {
    //验证规则
    var validatePhone = (rule, value, callback) => {
      const reg =
        /^0?(13[0-9]|15[012356789]|18[0-9]|14[578]|16[6]|17[035768]|19[19])[0-9]{8}$/;
      if (reg.test(value)) {
        return callback();
      }
      callback("请输入合法的手机号!");
    };
    var validateUserName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名或手机号!"));
      } else if (value.length < 8 || value.length > 16) {
        callback(new Error("用户名或手机号输入错误!"));
      } else {
        callback();
      }
    };
    var validatePassWord = (rule, value, callback) => {
      var reg =
        /^(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z\W]+$)(?![a-z\d]+$)(?![a-z\W]+$)(?![\d\W]+$)\S{8,16}$/;
      if (value === "") {
        callback(new Error("请输入密码!"));
      } else if (value.length < 8 || value.length > 16) {
        callback(new Error("请输入8~16位密码!"));
      } else if (!reg.test(value)) {
        callback(new Error("密码至少需含大小写、特殊字符、数字中的三种!"));
      } else {
        callback();
      }
    };
    var validateLoginWord = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码!"));
      } else {
        callback();
      }
    };
    return {
      userID: "", //接收登录后的用户ID
      perPath: "",
      currentIndex: "login1",
      show: true, // 初始启用按钮
      count: 60, // 初始化次数
      timer: null,
      codeVal: "",
      temp: "",
      loginForm1: {
        username: "",
        password: "",
      },
      loginForm2: {
        phone: "",
        loginword: "",
      },
      activeTab: "login1",
      rules: {
        username: [
          {
            validator: validateUserName,
            trigger: "blur",
          },
        ],
        password: [
          {
            validator: validatePassWord,
            trigger: "blur",
          },
        ],
        phone: [
          {
            validator: validatePhone,
            trigger: "blur",
          },
        ],
        loginword: [
          {
            validator: validateLoginWord,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    ...mapMutations("login", ["setUser"]),
    accountInput(val) {
      let codeReg = new RegExp("[A-Za-z0-9]+"), //正则 英文+数字；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.loginForm1.username = str;
    },
    passwordInput(val) {
      let codeReg = new RegExp("[A-Za-z0-9~!@#$%&*()_+-=<>,.?;:]+"), //正则 英文+数字+特殊字符；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.loginForm1.password = str;
    },
    phoneInput(val) {
      let codeReg = new RegExp("[0-9]+"), //正则 数字；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.loginForm2.phone = str;
    },
    loginWordInput(val) {
      let codeReg = new RegExp("[0-9]+"), //正则 英文+数字+特殊字符；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.loginForm2.loginword = str;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.activeTab === "login1") {
            //密码登录
            var login = new URLSearchParams();
            login.append("account", this.loginForm1.username);
            login.append("pswd", this.loginForm1.password);
            api.tryLogin(login).then((res) => {
              if (res.data == "") {
                this.$message.error("账号或密码错误!");
              } else {
                this.setUser(res.data);
                localStorage.setItem("shuXiang", JSON.stringify(res.data));
                //登陆成功，跳转到主页
                this.$message({
                  message: "登陆成功!",
                  type: "success",
                });
                this.$router.push({
                  path: this.perPath,
                  params: {
                    userID: this.userID,
                  },
                });
              }
            });
          }
          if (this.activeTab === "login2") {
            // console.log(this.loginForm2)
            if (this.temp !== "" && this.temp !== this.loginForm2.phone) {
              //发送的验证码与手机号不匹配
              this.$message.error("输入的验证码有误!");
            } else {
              console.log(this.codeVal);
              //判断当前用户输入的验证码是否与发送的验证码一致
              if (this.codeVal != this.loginForm2.loginword) {
                //用户输入的验证码不匹配
                this.$message.error("验证码错误!");
              } else {
                let param = new URLSearchParams();
                param.append("phoneNumber", this.loginForm2.phone);
                api.login(param).then((res) => {
                  this.setUser(res.data);
                  localStorage.setItem("shuXiang", JSON.stringify(res.data));
                  console.log(this.perPath);
                  this.$router.push({
                    path: this.perPath,
                    params: {
                      userID: this.userID,
                    },
                  });
                });
              }
            }
          }
        } else {
          return;
        }
      });
    },
    retrievePWD() {
      this.$router.push({ path: "/resPWD" });
    },
    toRegister() {
      this.$router.push({ path: "/register" });
    },
    handleTabsClick(tab) {
      console.log(tab.name);
      this.activeTab = tab.name;
    },
    getCode() {
      this.$refs["loginForm2"].validateField("phone", (err) => {
        if (err) {
          return;
        } else {
          // console.log('已通过')
          let param = new URLSearchParams();
          param.append("phoneNumber", this.loginForm2.phone);
          api.isPhoneRegistered(param).then((res0) => {
            // console.log(res0.data);
            if (res0.data == "1") {
              //发送验证码
              api.getAuthCode(param).then((res) => {
                this.tackBtn(); //验证码倒数60秒
                this.temp = this.loginForm2.phone;
                if (res.data == "-1") {
                  return;
                } else {
                  this.codeVal = res.data;
                }
              });
            } else {
              this.$message.error("您的手机号未注册!请前往注册!");
            }
          });
        }
      });
    },
    tackBtn() {
      if (this.loginForm2.phone)
        if (!this.timer) {
          this.count = 60;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= 60) {
              this.count--;
            } else {
              this.show = true;
              clearInterval(this.timer); // 清除定时器
              this.timer = null;
            }
          }, 1000);
        }
    },
  },
  created() {
    if (this.$route.query.perPath) {
      this.perPath = this.$route.query.perPath;
      this.perPath = this.perPath.substr(1);
    } else {
      this.perPath = "/home";
    }
  },
};
</script>

<style lang="less" scoped>
.block {
  position: fixed;
  height: 100%;
  width: 100%;
  position: fixed;
  background: url("../static/image/back.jpg");
  background-size: cover;
  .login {
    margin-top: 10%;
    margin-left: 45%;
    .box-card {
      border: 2px solid #bdbfc1;
      background: rgba(255, 255, 255, 0.8);
      margin: 0 auto;
      border-radius: 15px;
      width: 500px;
      height: 400px;
    }
    .el-card .box-card .is-always-shadow {
      .el-card__header {
        border-bottom: 1px solid black;
      }
    }
  }
}
</style>
